<template>
  <div class="search-container">
    <!-- 搜索栏 -->
    <form action="/">
      <van-search
        background="rgb(49, 150, 250)"
        v-model="searchTxt"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch(searchTxt)"
        @cancel="$router.back()"
        @focus="isResultShow = false"
      />
    </form>
    <!-- 搜索结果 -->
    <search-result v-if="isResultShow" :search-txt="searchTxt"></search-result>
    <!-- 联想建议 -->
    <search-suggest v-else-if="searchTxt" @search="onSearch" :search-txt="searchTxt"></search-suggest>
    <!-- 历史记录 -->
    <search-history v-else :search-history-list="searchHistoryList" @search="onSearch" @update-histories='searchHistoryList=$event'></search-history>

  </div>
</template>
<script>
import { mapState } from 'vuex'
import SearchSuggest from './components/SearchSuggest'
import SearchHistory from './components/SearchHistory'
import SearchResult from './components/SearchResult'
import { getSearchHistories } from '@/apis/search'
import { getItem, setItem } from '@/utils/storage'
export default {
  name: 'Search',
  components: {
    SearchSuggest,
    SearchHistory,
    SearchResult
  },
  data () {
    return {
      searchTxt: '',
      isResultShow: false,
      searchHistoryList: []
    }
  },
  watch: {
    searchHistoryList () {
      setItem('searchHistoryList', this.searchHistoryList)
    }
  },
  computed: {
    ...mapState([
      'userToken'
    ])
  },
  async created () {
    let searchHistories = getItem('searchHistoryList') || []
    if (this.userToken) {
      const { data } = await getSearchHistories()
      searchHistories = [...new Set([...searchHistories, ...data.data.keywords])]
      this.searchHistoryList.push(...data.data.keywords)
    }
    this.searchHistoryList = searchHistories
  },
  methods: {
    onSearch (val) {
      this.searchTxt = val

      // 记录历史
      let index = this.searchHistoryList.indexOf(val)
      if (index !== -1) {
        this.searchHistoryList.splice(index, 1)
      }
      this.searchHistoryList.unshift(val)

      // 展示搜索结果
      this.isResultShow = true
    }
  }
}
</script>
<style lang="less" scoped>
.search-container{
  .van-search__action{
    color: #fff;
  }
}
</style>
